package com.imflea.zero.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.model.dao.user.WebUserFriendMapper;
import com.imflea.zero.model.entity.user.WebUserFriend;
import com.imflea.zero.model.entity.user.WebUserInfo;
import com.imflea.zero.model.entity.user.dto.FriendQueryDto;
import com.imflea.zero.model.entity.user.dto.WebUserFriendDto;
import com.imflea.zero.model.entity.user.vo.UserFriendVo;
import com.imflea.zero.service.user.IWebUserFriendService;
import com.imflea.zero.service.user.IWebUserInfoService;
import com.imflea.zero.utils.SessionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 好友关系表 服务实现类
 * </p>
 *
 * @author xiangbaoyu
 * @since 2021-09-23
 */
@Service
public class WebUserFriendServiceImpl extends ServiceImpl<WebUserFriendMapper, WebUserFriend> implements IWebUserFriendService {
    @Autowired
    private IWebUserInfoService webUserInfoService;

    @Override
    public WebUserFriend saveOrUpdateWebUserFriend(WebUserFriend entity) {
        if (CommonUtils.isNull(entity.getId())) {
            entity.setId(CommonUtils.generateRandomString());
        }
        entity.setTenantId(SessionUtils.getTenantId());
        boolean result = this.saveOrUpdate(entity);
        if (!result) {
            throw new BizException("操作失败，请联系管理员！");
        }
        return entity;
    }

    @Override
    public PageInfo<WebUserFriend> queryPage(WebUserFriendDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<WebUserFriend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", tenantId);
        PageHelper.startPage(pageIndex, pageSize);
        List<WebUserFriend> adoptInfos = this.list(queryWrapper);
        PageInfo<WebUserFriend> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public List<UserFriendVo> queryAll(FriendQueryDto friendQueryDto) {
        QueryWrapper<WebUserFriend> queryWrapper = new QueryWrapper<>();
        String tenantId = SessionUtils.getTenantId();
        String userId = SessionUtils.getUserId();
        String remarksName = friendQueryDto.getRemarksName();
        queryWrapper.eq("tenant_id", tenantId);
        queryWrapper.eq("user_id", userId);

        if (!CommonUtils.isNull(remarksName)) {
            queryWrapper.like("remarks_name", remarksName);
        }
        List<WebUserFriend> friends = this.list(queryWrapper);
        if (CommonUtils.isNull(friends)) {
            return new ArrayList<>();
        }
        List<WebUserFriend> fs = friends.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(WebUserFriend::getFriendId))), ArrayList::new));

        Map<String, WebUserFriend> friendMap = fs.stream().collect(Collectors.toMap(WebUserFriend::getFriendId, friend -> friend));
        List<String> userIds = friends.stream().map(WebUserFriend::getFriendId).collect(Collectors.toList());
        List<WebUserInfo> userInfos = webUserInfoService.listByIds(userIds);
        List<UserFriendVo> friendVos = new ArrayList<>();

        for (WebUserInfo info : userInfos) {
            UserFriendVo friendVo = new UserFriendVo();
            WebUserFriend tempFriend = friendMap.get(info.getId());
            friendVo.setId(tempFriend.getId());
            friendVo.setFriendId(info.getId());
            friendVo.setRemarksName(tempFriend.getRemarksName());
            friendVo.setNickName(info.getNickName());
            friendVo.setCellNum(info.getCellNum());
            friendVo.setCreateTime(tempFriend.getCreateTime());
            friendVo.setAvatarUrl(info.getAvatarUrl());
            friendVos.add(friendVo);

        }

        return friendVos;
    }

    @Override
    public WebUserFriend saveFriend(WebUserFriend invite) {
        //发起邀请人:不设置备注
        invite.setId(CommonUtils.generateRandomString());
        String tenantId = SessionUtils.getTenantId();
        invite.setTenantId(tenantId);
        invite.setFriendId(SessionUtils.getUserId());
        LocalDateTime now = LocalDateTime.now();
        invite.setCreateTime(now);


        //接收人
        WebUserFriend invited = new WebUserFriend();
        invited.setId(CommonUtils.generateRandomString());
        invited.setRemarksName(invite.getRemarksName());
        invited.setFriendId(invite.getUserId());
        invited.setCreateTime(now);
        invited.setTenantId(tenantId);
        invited.setUserId(SessionUtils.getUserId());


        List<WebUserFriend> friends = new ArrayList<>();
        //需要校验是否已经是好友


        boolean isExist = this.query4checkIsExist(invite.getUserId(), SessionUtils.getUserId());
        if (!isExist) {
            friends.add(invite);
        }
        boolean isExist2 = this.query4checkIsExist(SessionUtils.getUserId(), invite.getUserId());
        if (!isExist2) {
            friends.add(invited);
        }
        if (!CommonUtils.isNull(friends)) {
            boolean result = this.saveBatch(friends);
            if (!result) {
                throw new BizException("好友添加失败！");
            }
        }
        return invite;


    }

    @Override
    public boolean removeFriendsById(String id) {

        WebUserFriend self = this.getById(id);
        if (CommonUtils.isNull(self)) {
            throw new BizException("好友关系不存在");
        }
        String userId = SessionUtils.getUserId();//当前用户id，校验，
        String friendUserId = self.getUserId();

        if (!userId.equals(friendUserId)) {
            throw new BizException("越权操作，操作关系为非当前朋友关系");
        }
        QueryWrapper<WebUserFriend> queryWrapper = new QueryWrapper<>();
        String friendId = self.getFriendId();
        String tenantId = SessionUtils.getTenantId();
        queryWrapper.eq("tenant_id", tenantId);
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("friend_id", friendId);
//        queryWrapper.and(wrapper -> wrapper.eq("user_id", userId).eq("friend_id", friendId).or(rapper -> rapper.eq("friend_id", userId).eq("user_id", friendId)));

        List<WebUserFriend> friendInfos = this.list(queryWrapper);
        List<String> ids = new ArrayList<>();
        ids.add(id);
        if (CommonUtils.isNull(friendInfos)) {
            ids = friendInfos.stream().map(WebUserFriend::getId).collect(Collectors.toList());
        }
        boolean result = this.removeByIds(ids);
        if (!result) {
            throw new BizException("解除好友关系失败");
        }

        return result;
    }

    public boolean query4checkIsExist(String inviteId, String invitedId) {
        QueryWrapper<WebUserFriend> queryWrapper = new QueryWrapper<>();
        String tenantId = SessionUtils.getTenantId();
        queryWrapper.eq("user_id", inviteId);
        queryWrapper.eq("friend_id", invitedId);
        queryWrapper.eq("tenant_id", tenantId);

        List<WebUserFriend> friends = this.list(queryWrapper);
        if (CommonUtils.isNull(friends)) {
            return false;
        } else {
            return true;
        }
    }

}
